<script setup lang="tsx">
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import QueryBox from '@/components/queryBox/index.vue';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import TinymceEditor from '@/components/tinymceEditor/index.vue';
import IageViewer from '@/components/imageViewer/index.vue';
import UpLoad from '@/components/upLoad/index.vue';
import Category from './components/category.vue';
import { Space, Link, MessagePlugin } from 'tdesign-vue-next';
import { AddIcon, Delete1Icon } from 'tdesign-icons-vue-next';
import { getList, add, edit, getInfo, Delete } from '@/api/system/InternalAnnouncement';
import { getCategoryList } from '@/api/system/InternalAnnouncement';
import { getLangList } from '@/api/system/basicSetting/7';
import { getName } from '@/utils/tool';
const { t } = useI18n();
const data = ref([]);
const columns = [
  {
    colKey: 'row-select',
    type: 'multiple' as const,
    width: 50,
  },
  {
    title: 'ID',
    colKey: 'noticeId',
  },
  {
    title: '公告标题',
    colKey: 'title',
  },
  {
    title: '公告分类',
    colKey: 'gropid',
  },
  {
    title: '语言',
    colKey: 'lang',
  },
  {
    title: '图片',
    colKey: 'coverImg',
  },
  {
    title: '阅读量',
    colKey: 'view',
  },
  {
    title: '排序',
    colKey: 'sort',
  },
  {
    title: '添加时间',
    colKey: 'createTime',
  },
  {
    title: '操作',
    colKey: 'op',
  },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <AddIcon />} onClick={() => unAdd()}>
        新增
      </t-button>
      <t-button onClick={() => openCategory()}>公告分类</t-button>
      <t-button theme="danger" icon={() => <Delete1Icon />} onClick={() => deleteClickOp(deleteId.value, true)}>
        批量删除
      </t-button>
    </OperatingBox>
    <QueryBox onReset={onReset} v-model:defaultCurrent={pagination.value.defaultCurrent} onSearch={unGetList}>
      <t-select v-model={queryForm.value.gropid} placeholder="公告分类">
        {categoryList.value?.map((item) => <t-option key={item.ncId} label={item.title} value={item.ncId} />)}
      </t-select>
      <t-select v-model={queryForm.value.lang} placeholder="语言">
        {langList.value?.map((item) => <t-option key={item.code} label={item.name} value={item.code} />)}
      </t-select>
    </QueryBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      v-model:selectedRowKeys={deleteId.value}
      rowKey="noticeId"
      onUnGetList={unGetList}
    >
      {{
        gropid: (slotProps: any) => <div>{getName('ncId', slotProps.row.gropid, categoryList.value, 'title')}</div>,
        lang: (slotProps: any) => <div>{getName('code', slotProps.row.lang, langList.value, 'name')}</div>,
        coverImg: (slotProps: any) => (
          <div>
            {slotProps.row.coverImg && <IageViewer img={import.meta.env.VITE_PROXY_API_URL + slotProps.row.coverImg} />}
          </div>
        ),
        op: (slotProps: any) => (
          <Space>
            <Link theme="primary" onClick={() => unEdit(slotProps)}>
              修改
            </Link>
            <Link theme="danger" onClick={() => deleteClickOp(slotProps, false)}>
              {t('pages.detailCard.detail.form.delete')}
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

interface FormDataType {
  gropid: string | number | null;
  lang: string | number | null;
  pageNum: string | number | null;
  pageSize: string | number | null;
}
const INITIAL_QUERYFORM: FormDataType = {
  gropid: undefined,
  lang: undefined,
  pageNum: null,
  pageSize: null,
};
const queryForm = ref({ ...INITIAL_QUERYFORM });

const unGetList = async () => {
  try {
    const res = await getList({
      ...queryForm.value,
      pageNum: pagination.value.defaultCurrent,
      pageSize: pagination.value.defaultPageSize,
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};

unGetList();
const langList = ref<any[]>([]);
// 获取语言
const unGetLangList = async () => {
  try {
    const res = await getLangList({
      pageNum: 1,
      pageSize: 999,
      status: 1,
    });
    langList.value = res.rows;
  } catch (e) {
    console.log(e);
  }
};
unGetLangList();
const categoryList = ref<any[]>([]);
// 获取公告类别
const unGetCategoryList = async () => {
  try {
    const res = await getCategoryList({
      pageNum: 1,
      pageSize: 999,
    });
    categoryList.value = res.rows;
  } catch (e) {
    console.log(e);
  }
};
unGetCategoryList();

/** 添加对话框 */
const formObj = new formGroup();
const unAdd = async () => {
  try {
    formObj.show('添加公告', {}, '添加公告');
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};
formObj.add<any>(
  '添加公告',
  '添加公告',
  {},
  async (body) => {
    await add(body.data);
    unGetList();
  },
  {
    title: [{ required: true, message: '公告标题不能为空', trigger: 'blur' }],
  },
  '50%',
);

// 公告详情
const unEdit = async (slotProps: any) => {
  try {
    let res = await getInfo(slotProps.row.noticeId);
    formObj.show(
      '编辑公告',
      {
        ...res.data,
      },
      '编辑公告',
    );
  } catch (e) {
    console.error('获取公告详情失败:', e);
    MessagePlugin.error('获取公告详情失败');
  }
};

formObj.add<any>(
  '编辑公告',
  '编辑公告',
  {},
  async (body) => {
    await edit(body.data);
    unGetList();
  },
  {
    nickName: [{ required: true, message: '公告标题不能为空', trigger: 'blur' }],
  },
  '50%',
);

// 删除
const confirmVisible = ref(false);
const deleteId = ref([]);
const onConfirmDelete = () => {
  let ids = deleteId.value.join(',');
  Delete(ids).then(() => {
    confirmVisible.value = false;
    MessagePlugin.success('删除成功');
    unGetList();
  });
};

const deleteClickOp = (value: any, isSingle: boolean) => {
  if (isSingle && !value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  confirmVisible.value = true;
  deleteId.value = isSingle ? value : [value.row.noticeId];
};

const onCancel = () => {
  if (deleteId.value.length < 2) {
    deleteId.value = [];
  }
};

// 公告分类
const category = ref();
const openCategory = () => {
  category.value.open();
};

// 搜索
const onReset = () => {
  queryForm.value = { ...INITIAL_QUERYFORM };
  unGetList();
};
</script>

<template>
  <div>
    <render />
    <!-- 对话框 -->
    <FormDialogGroup :form-obj="formObj">
      <template #default="{ formData, item }">
        <template v-if="item == '添加公告' || item == '编辑公告'">
          <t-form-item label="公告标题" name="title">
            <t-input v-model="formData.title" :style="{ width: '480px' }" placeholder="请输入公告标题" />
          </t-form-item>
          <t-form-item label="公告分类" name="gropid">
            <t-select v-model="formData.gropid" :style="{ width: '480px' }">
              <t-option v-for="item in categoryList" :key="item.ncId" :label="item.title" :value="item.ncId" />
            </t-select>
          </t-form-item>
          <t-form-item label="语言" name="lang">
            <t-select v-model="formData.lang" :style="{ width: '480px' }">
              <t-option v-for="item in langList" :key="item.code" :label="item.name" :value="item.code" />
            </t-select>
          </t-form-item>
          <t-form-item label="链接" name="url">
            <t-input v-model="formData.url" :style="{ width: '480px' }" placeholder="请输入公告链接" />
          </t-form-item>
          <t-form-item label="阅读量" name="view">
            <t-input-number v-model="formData.view" :style="{ width: '480px' }" placeholder="请输入阅读量" />
          </t-form-item>
          <t-form-item label="排序" name="sort">
            <t-input-number v-model="formData.sort" :style="{ width: '480px' }" placeholder="排序值" />
          </t-form-item>
          <t-form-item label="缩略图" name="coverImg">
            <UpLoad v-model:image="formData.coverImg" :key="formData.coverImg"></UpLoad>
          </t-form-item>
          <t-form-item label="公告内容" name="content">
            <TinymceEditor v-model="formData.content" ref="editor"></TinymceEditor>
          </t-form-item>
        </template>
      </template>
    </FormDialogGroup>
    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选项目？"
      body="删除后，数据将被清空，且无法恢复"
      @confirm="onConfirmDelete"
      :on-cancel="onCancel"
    />

    <!-- 公告分类 -->
    <Category @unGetCategoryList="unGetCategoryList" ref="category"></Category>
  </div>
</template>
